package com.example.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@ControllerAdvice  //Controller的增强类
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;   //表示是否对ResponseBody进行增强，返回true
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        //后端返回结果之前，先拿到对象o对其进行统一数据格式封装，然后再返回前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("status",0);  //返回的状态
        map.put("data",o);    //程序返回的结果，举例对于查询而言，返回的就是user对象
        map.put("msg","");    //普通的信息，类似错误信息提示

//        if(o instanceof  String){
//            //响应头中设置Json类型，当前方法返回给前端一个Json字符串
//            serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
//            objectMapper.writeValueAsString(map);
//        }
        //Controller中方法已经加入了@ResponseBody注解，因此spring将map对象直接转换为Json字符串
        return map;
    }
}
